<?php
//+--------------------------------------------
//|描述 php-redis 单例模式
//|--------------------------------------------
//|Created by PhpStorm.
//| Author: DRG
//+-------------------------------------------
//|Date: 2018/6/5
//| Time: 11:52
//+--------------------------------------------

namespace app\common\lib;

class Predis {
    public $redis = "";
    /**
     * 定义单列模式的变量
     * @var null
     */
    private  static $_instance = null;
    
    public static function getInstance()
    {
        if(empty(self::$_instance)){
            self::$_instance = new self();
        }
            return self::$_instance;
        
    }
    private function __construct()
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeout'));
        $this->redis->select(config('redis.redis_db'));
        if($result == false){
            throw  new \Exception('redis connect error');
        }
    }
    
    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     * @author DRG
     */
    public function set($key, $value, $time=0)
    {
        if(!$key){
            return '';
        }
        
        if(is_array($value)){
            $value = json_encode($value);
        }
        if(!$time){
            return $this->redis->set($key, $value);
        }
        
        return $this->redis->setex($key, $time, $value);
    }
    
    public function get($key)
    {
        if(!$key){
            return '';
        }
        return $this->redis->get($key);
    }
    
    /**
     * 设置无序集合
     * @param $key
     * @param $val
     */
    public function sadd($key, $val)
    {
        return $this->redis->sAdd($key, $val);
    }
    
    /**
     * @param $key
     * @param $value
     * @return int
     * @author DRG
     * 删除c操作
     */
    public function sremove($key, $value)
    {
        return $this->redis->sRem($key, $value);
    }
    
    /**
     * 获取无需集合
     * @param $key
     * @return array
     */
    public function sMembers($key) {
        return $this->redis->sMembers($key);
    }
    
    /**
     *
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments) {
        //echo $name.PHP_EOL;
        //print_r($arguments);
        if(count($arguments) != 2) {
            return '';
        }
        $this->redis->$name($arguments[0], $arguments[1]);
    }
}